package com.zijin.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

/**
 * @Title: PythonUtils
 * @Author JWei Xu
 * @Package com.zijin.utils
 * @Date 2024/12/27 11:11
 * @description: 提供与python文件的交互能力
 */

@Slf4j
public class PythonUtils {
    public static String runPythonApplication(String pythonScriptPath,String imagePath){
        // Python解释器的路径（包括双引号，以应对路径中包含空格的情况）
        String pythonExePath = "E:\\Program Files\\Python39\\python.exe";

        // 构建命令字符串数组，每个元素对应一个命令行参数
        String[] command = {"cmd", "/c", pythonExePath, pythonScriptPath, imagePath};

        String sout = "";
        try {
            // 启动Python脚本
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sout = sout+line+"\n";
            }
            int exitCode = process.waitFor();
            sout = sout+ "Exit Code: " + exitCode+"\n";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sout;
    }

    /**
     *
     * @Author: JiaWei Xu
     * @Date: 2025/2/18
     * @Params: pythonScriptPath Python 脚本的地址 instructions 指令
     * @Return:
     * @Description:
     */

    public static String runPythonApplication(String pythonScriptPath, String[] instructions){
        // Python解释器的路径（包括双引号，以应对路径中包含空格的情况）
        String pythonExePath = "E:\\Program Files\\Python39\\python.exe";

        // 构建命令字符串数组，每个元素对应一个命令行参数
        String[] front  = {"cmd", "/c", pythonExePath, pythonScriptPath};

        String[] command = new String[front.length+instructions.length];

        System.arraycopy(front, 0, command, 0, front.length);
        System.arraycopy(instructions, 0, command, front.length, instructions.length);

        String sout = "";
        log.info(Arrays.toString(command));
        try {

            // 启动Python脚本
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
            String line;
            while ((line = reader.readLine()) != null) {
                sout = sout+line+"\n";
            }
            int exitCode = process.waitFor();
            sout = sout+ "Exit Code: " + exitCode+"\n";
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(sout);
        return sout;
    }

}
